package com.socialnetwork.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.socialnetwork.control.ActionController;
import com.socialnetwork.util.UtilFormat;
import com.socialnetwork.util.UtilString;

/**
 * Servlet implementation class ServletController
 */
@WebServlet(name="servletController", urlPatterns = {"*.action"})
public class ServletController extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public ServletController() {
    }
    
    /**
     * 
     * @param request
     * @param response
     * @throws IOException 
     * @throws ServletException 
     */
    public void processMethod(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    	
    	System.out.println("\nINIT - ServletController");
    	
    	String servletPath = request.getServletPath();
    	String classNameController = UtilFormat.formatNameController(servletPath);
		
		try {
			if(classNameController != null && !classNameController.equals("")){
				Class classController = Class.forName(UtilString.PACKAGE_CONTROLLER + classNameController);
				ActionController controller = (ActionController) classController.newInstance();
				System.out.println("EXECUTE CONTROLLER = " + classNameController);
				controller.execute(request, response);
			}else{
				System.out.println("ERROR - NO FOUND CLASS NAME CONTROLLER");
			}
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		
		System.out.println("END - ServletController");
		
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		processMethod(request, response);
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		processMethod(request, response);
		
	}

}
